package com.cloudspace.jindun.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.cloudspace.jindun.R;
import com.cloudspace.jindun.callback.AuthCodeInputCallback;
import com.cloudspace.jindun.log.APPLog;
import com.cloudspace.jindun.utils.MMAlert;
import com.cloudspace.jindun.utils.MyDialog;
import com.cloudspace.jindun.utils.ToastMaker;

/**
 * Created by zengxianhua on 17/3/2.
 */

public class AuthDialog {
    private MyDialog mEnterChannelPasswordDlg;
    private Activity activity;

    public AuthDialog(Activity activity){
        this.activity = activity;
    }

    public void show(final AuthCodeInputCallback callback){
        if (activity == null){
            return;
        }

        if (mEnterChannelPasswordDlg == null){
            View view = View.inflate(activity, R.layout.enter_channale_password, null);
            mEnterChannelPasswordDlg = MMAlert.showAlert(activity,
                    activity.getResources().getString(R.string.enter_channel_pasword_dialog_title),
                    view,
                    activity.getResources().getString(R.string.enter_channel_ok),
                    activity.getResources().getString(R.string.enter_channel_cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String code = getCode();

                            if (TextUtils.isEmpty(code)){
                                ToastMaker.showToastShort(R.string.channel_input_password_notvalid);
                                return;
                            }
                            if (callback != null){
                                callback.onFinish(code);
                            }
                        }
                    },
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            reset();
                        }
                    }
            );

            et1 = (EditText) mEnterChannelPasswordDlg.findViewById(R.id.digit_edit1);
            et2 = (EditText) mEnterChannelPasswordDlg.findViewById(R.id.digit_edit2);
            et3 = (EditText) mEnterChannelPasswordDlg.findViewById(R.id.digit_edit3);
            et4 = (EditText) mEnterChannelPasswordDlg.findViewById(R.id.digit_edit4);

            et1.setTag(1);
            et2.setTag(2);
            et3.setTag(3);
            et4.setTag(4);

            et1.addTextChangedListener(new MyTextChangeWatcher(1));
            et2.addTextChangedListener(new MyTextChangeWatcher(2));
            et3.addTextChangedListener(new MyTextChangeWatcher(3));
            et4.addTextChangedListener(new MyTextChangeWatcher(4));

            et1.setOnKeyListener(keyListener);
            et2.setOnKeyListener(keyListener);
            et3.setOnKeyListener(keyListener);
            et4.setOnKeyListener(keyListener);
        }else{
            mEnterChannelPasswordDlg.show();
        }

    }

    private void reset() {
        if (et1 != null){
            et1.setText("");
        }

        if (et2 != null){
            et2.setText("");
        }

        if (et3 != null){
            et3.setText("");
        }

        if (et4 != null){
            et4.setText("");
        }
    }

    private String getCode() {
        String digit1 = et1.getEditableText().toString();
        String digit2 = et2.getEditableText().toString();
        String digit3 = et3.getEditableText().toString();
        String digit4 = et4.getEditableText().toString();

        if (TextUtils.isEmpty(digit1) ||
                TextUtils.isEmpty(digit2) || TextUtils.isEmpty(digit3) || TextUtils.isEmpty(digit4)){

            return "";
        }

        String password = digit1 + digit2 + digit3 + digit4;
        return password;
    }

    private  EditText et1;
    private  EditText et2;
    private  EditText et3;
    private  EditText et4;
    private  int flag;

    public void hide() {
        if (mEnterChannelPasswordDlg != null && mEnterChannelPasswordDlg.isShowing()){
            mEnterChannelPasswordDlg.dismiss();
            mEnterChannelPasswordDlg = null;
        }

        reset();
    }



    class MyTextChangeWatcher implements TextWatcher {
        //标示 绑定的EditText
        private int index;

        public MyTextChangeWatcher(int index) {
            super();
            this.index = index;
        }

        @Override
        public void afterTextChanged(Editable s) {
            APPLog.d("afterTextChanged --s=" + s.toString());
            if (s != null && s.length() == 1) {
                if (index < 4) {// 焦点后移
                    getEditTextFromIndex(index).clearFocus();
                    getEditTextFromIndex(index + 1).requestFocusFromTouch();
                }
                setFlag(false, index);// 对应标志位 置 1
                //有内容输入，判断密码是否输入OK

            } else {
                //清除 对应 标识位
                setFlag(true, index);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            APPLog.d("beforeTextChanged --s=" + s.toString());

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            APPLog.d("onTextChanged --s=" + s.toString());

        }

    }

    private EditText getEditTextFromIndex(int index) {
        switch (index) {
            case 1 :
                return et1;
            case 2 :
                return et2;
            case 3 :
                return et3;
            case 4 :
                return et4;

            default :
                break;
        }
        return et1;
    }

    /**
     * 监听删除键 前移焦点
     */
    private View.OnKeyListener keyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((((EditText) v).getText().toString() == null || ((EditText) v)
                    .getText().toString().isEmpty())
                    && keyCode == KeyEvent.KEYCODE_DEL
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                // 该EditText的 内容已为空，并且 del 键按下
                v.clearFocus();// 清除该控件焦点
                // 将焦点给到前面一个EditText
                EditText editText = getEditTextFromIndex(Integer
                        .parseInt(String.valueOf(v.getTag())) - 1);
                // editText.requestFocus(); //也可以
                editText.requestFocusFromTouch();
            }

            return false;
        }
    };

    private void setFlag(boolean isNull, int index) {
        // 得到 唯一一个 1的二进制数 00001000
        byte b = (byte) (1 << (index - 1));
        if (isNull) {// 指定 位 清零
            b = (byte) ~b; // 11110111
            flag = (byte) (flag & b);
        } else {// 制定位 赋值 1
            flag = (byte) (flag | b);
        }
    }
}
